package com.zsh.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class SessionServlet extends BaseServlet {

        protected void deleteNow(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            HttpSession session = request.getSession();
            session.invalidate();
            response.getWriter().write("session立马删除");
        }

        protected void life3(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

            HttpSession session = request.getSession();
            session.setMaxInactiveInterval(3);
            response.getWriter().write("3s后session消除");
        }

        protected void defaultLife(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

            response.setContentType("text/html;charset=UTF-8");
            int maxInactiveInterval = request.getSession().getMaxInactiveInterval();
            response.getWriter().print(maxInactiveInterval);
        }

        protected void setAttribute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            request.getSession().setAttribute("key1","value1");

        }

        protected void getAttribute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            Object value = request.getSession().getAttribute("key1");
            response.getWriter().write(value.toString());
        }

        protected void createOrGetSession(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //创建或获取session对象
        HttpSession session = request.getSession();

        //判断session是否是新创建的
        boolean isNew = session.isNew();

        //获取session对话的唯一标识
        String id = session.getId();

        response.getWriter().write(id + "<br/>");
        response.getWriter().write("" + isNew);
    }

}
